package com.cxyw.qqrobot.service;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.cxyw.qqrobot.Util;
import com.cxyw.qqrobot.domain.NiuZi;
import com.cxyw.qqrobot.domain.OpenShaMrock;
import com.cxyw.qqrobot.mapper.NiuZiMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;


@Service
@Slf4j
public class QQRobotService {


    @Resource
    OpenShaMrock openShaMrock;

    @Resource
    NiuZiMapper niuZiMapper;

    @Resource
    RedisService redisService;

    @Resource
    SeTuService seTuService;

    @Value("${qqrobot.sleepTime}")
    public  int sleepTime;


    @Value("${qqrobot.se_tu_cooling_time}")
    public int se_tu_cooling_time;

//    group_id	int64	是	群号
//    message	string / object / array	是	消息内容
//    auto_escape	bool	否	是否解析 CQ 码（true为不解析）。
//    recall_duration	int64	否	自动撤回时间间隔（毫秒）

    @Data
    public class SendGroupReqBody {
        private Long group_id;
        private Object message;
        private Boolean auto_escape;
        private Long recall_duration;

        public SendGroupReqBody(long group_id, Object message) {
            this.group_id = group_id;
            this.message = message;
        }


        public SendGroupReqBody(long group_id, Object message, boolean auto_escape, long recall_duration) {
            this.group_id = group_id;
            this.message = message;
            this.auto_escape = auto_escape;
            this.recall_duration = recall_duration;
        }

    }
    public void sendGroup(long groupId, String message) {
        String url=StrUtil.format("http://{}:{}/{}",openShaMrock.ip,openShaMrock.port,openShaMrock.sendGroupUrl);
        // 构建请求头
        HttpResponse execute = HttpRequest.post(url).
                header("content-type", "application/json; charset=utf-8").
                body(JSONObject.toJSONString(new SendGroupReqBody(groupId, message))).execute();
    }


    public void handleQQMessage(String message) {
        Util.MsgBody msgBody = Util.getMsgBody(message);
        //非群聊消息暂不处理
        if (null==msgBody || !msgBody.getMessageType().equals(Util.MsgType.GROUP_MESSAGE.getMessageType())) {
            return;
        }
        //遍历MsgSubType,全部都不匹配的话就返回
        if (!Util.MsgSubType.isSub(msgBody.getContent())) {
            return;
        }

        log.info("【websocket消息】收到客户端发来的消息:{}",message);
        //获取发送者qq号
        Long qqId = msgBody.getQq();
        //获取群号
        Long groupId = msgBody.getGroupId();
        String content = msgBody.getContent();
        NiuZi niuZi = niuZiMapper.selectById(qqId);

        if (content.equals(Util.MsgSubType.COME_ONE_SE_TU.getRemark())) {
            String key=Util.MsgSubType.COME_ONE_SE_TU.toString()+qqId;
            if (null != redisService.get(key)){
                long sleepTime = redisService.getExpire(key);
                sendGroup(groupId, StrUtil.format(Util.Desc.REPEAT_COME_ONE_SE_TU.getRemark(),sleepTime) );
                return;
            }
            String tag=null;
            String[] split = content.split("#");
            if (split.length>1){
                tag=split[1];
            }
            String seTuUrl=null==tag? seTuService.getSeTuByDb():seTuService.getSeTuByTag(tag);
            if (null == seTuUrl) {
                sendGroup(groupId, Util.Desc.NO_COME_ONE_SE_TU.getRemark());
                return;
            }
            redisService.set(key, "1", se_tu_cooling_time);
            sendGroup(groupId, StrUtil.format("[CQ:image,file={}]",seTuUrl));
            return;
        }

        if (content.equals(Util.MsgSubType.LEARN_DERIVATIVE.getRemark())) {
            if (null != niuZi) {
                sendGroup(groupId, Util.Desc.HAS_LEARN.getRemark());
                return;
            }
            niuZiMapper.insert(new NiuZi(qqId, 1, LocalDateTime.now()));
            sendGroup(groupId, Util.Desc.WILL_LEARN.getRemark());
            return;
        }
        if (content.equals(Util.MsgSubType.MY_DERIVATIVE.getRemark())) {
            if (null == niuZi) {
                sendGroup(groupId, Util.Desc.NO_LEARN.getRemark());
                return;
            }
            sendGroup(groupId, StrUtil.format(Util.Desc.MY_DERIVATIVE.getRemark(),niuZi.length) );
            return;
        }

        if (content.equals(Util.MsgSubType.START_DERIVATIVE.getRemark())) {
            if (null == niuZi) {
                sendGroup(groupId, Util.Desc.NO_LEARN.getRemark());
                return;
            }
            String key=Util.MsgSubType.START_DERIVATIVE.toString()+qqId;
            if (null != redisService.get(key)){
                long sleepTime = redisService.getExpire(key);
                sendGroup(groupId, StrUtil.format(Util.Desc.REPEAT_DERIVATIVE.getRemark(),sleepTime) );
                return;
            }
            redisService.set(key, "1", sleepTime);
            double increase = RandomUtil.randomDouble(0, 2);
            niuZi.setLength(niuZi.getLength() +increase );
            niuZiMapper.updateById(niuZi);
            sendGroup(groupId, StrUtil.format(Util.Desc.START_DERIVATIVE.getRemark(),increase) );
            return;
        }


        if (content.contains(Util.MsgSubType.FACE_DERIVATIVE.getRemark())) {
            Long atQQ=msgBody.getAtQQ();
            if (null==atQQ){
                sendGroup(groupId, Util.Desc.NO_AT_FACE_LOSE_DERIVATIVE.getRemark());
                return;
            }
            if (atQQ.equals(qqId)){
                sendGroup(groupId, Util.Desc.SAME_FACE_LOSE_DERIVATIVE.getRemark());
                return;
            }
            if (null == niuZi) {
                sendGroup(groupId, Util.Desc.NO_LEARN.getRemark());
                return;
            }
            NiuZi atNiuZi = niuZiMapper.selectById(atQQ);
            if (null == atNiuZi) {
                sendGroup(groupId, Util.Desc.AT_NO_LEARN.getRemark());
                return;
            }
            String key=Util.MsgSubType.FACE_DERIVATIVE.toString()+qqId;
            if (null != redisService.get(key)){
                long sleepTime = redisService.getExpire(key);
                sendGroup(groupId, StrUtil.format(Util.Desc.REPEAT_DERIVATIVE.getRemark(),sleepTime) );
                return;
            }
            redisService.set(key, "1", sleepTime);
            double random = Math.random();
            double increase = RandomUtil.randomDouble(0, 2);
            double decrease = RandomUtil.randomDouble(0, 2);
            String seTuUrl = seTuService.getSeTu();
            if (random>0.5){
                niuZi.setLength(niuZi.getLength() +increase );
                atNiuZi.setLength(atNiuZi.getLength() -decrease );
                niuZiMapper.updateById(niuZi);
                niuZiMapper.updateById(atNiuZi);
                log.info("已处理对导请求");;
                sendGroup(groupId,StrUtil.format("{} [CQ:image,file={}]",StrUtil.format(Util.Desc.FACE_WIN_DERIVATIVE.getRemark(),increase,decrease),seTuUrl));
                return;
            }
            niuZi.setLength(niuZi.getLength() -decrease );
            atNiuZi.setLength(atNiuZi.getLength() +increase );
            niuZiMapper.updateById(niuZi);
            niuZiMapper.updateById(atNiuZi);
            log.info("已处理对导请求");
            sendGroup(groupId,StrUtil.format("{} [CQ:image,file={}]",StrUtil.format(Util.Desc.FACE_LOSE_DERIVATIVE.getRemark(),decrease,increase),seTuUrl));
            return;
        }

    }


    @PostConstruct
    public void test(){
        System.out.printf("qqrobot已注册");
    }

    public static void main(String[] args) {
        System.out.println("1".split("#").toString());
    }
}
